package com.example.springbootshiro.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.springbootshiro.entity.ShiroUser;
import com.example.springbootshiro.service.ShiroUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author vicente
 * @since 2022-01-11
 */
@RestController
public class ShiroUserController {

    @Autowired
    private ShiroUserService userService;

    @RequestMapping("/testShiro")
    public String testShiro(){
        System.out.println("shiro过期时间为："+SecurityUtils.getSubject().getSession().getTimeout());
        return "success";
    }

    @RequestMapping("/getUserByName")
    public String getUserByName(String userName){
        ShiroUser user = userService.getUserByName(userName);
        return JSON.toJSONString(user);
    }

    //用户登录
    @RequestMapping("/login")
    public String loginUser(@RequestParam("username") String username,
                            @RequestParam("password") String password,
                            @RequestParam("rememberMe") boolean rememberMe,
                            HttpSession session) {
        //把前端输入的username和password封装为token
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            //subject.getSession().setTimeout(1000L);
            session.setAttribute("user", subject.getPrincipal());
            return "index";
        } catch (Exception e) {
            return "login";
        }
    }

    //退出登录
    @RequestMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            subject.logout();
        }
        return "login";
    }

    @RequestMapping("/add")
    public String add(){
        System.out.println("add---------------");
        return "add";
    }

    @RequestMapping("/delete")
    public String delete(){
        System.out.println("delete---------------");
        return "delete";
    }

    @RequestMapping("/403")
    public String getError(){
        System.out.println("未授权页面---------------");
        return "403";
    }

}
